import { fileURLToPath, URL } from 'node:url'
import { createHtmlPlugin } from 'vite-plugin-html'
import { defineConfig, loadEnv } from 'vite'
import vue from '@vitejs/plugin-vue'
import { generteNow } from './src/utils/dayjs'
import { createStyleImportPlugin, VantResolve } from 'vite-plugin-style-import'
const buildTime = generteNow()

export default ({ mode }) => {
  const env = loadEnv(mode, process.cwd())
  return defineConfig({
    plugins: [
      vue(),
      createHtmlPlugin({
        inject: {
          data: {
            injectScript: `<link rel="dns-prefetch" href=${env.VITE_API} />`,
          },
        },
      }),
      createStyleImportPlugin({
        resolves: [VantResolve()],
        libs: [
          {
            libraryName: 'vant',
            // esModule: true,
            resolveStyle: (name) => {
              if (name === 'show-toast') return 'vant/es/toast/style'
              if (name === 'close-toast') return 'vant/es/toast/style'
              return `vant/es/${name}/style`
            },
          },
        ],
      }),
    ],
    resolve: {
      alias: {
        '@': fileURLToPath(new URL('./src', import.meta.url)),
        '@utils': fileURLToPath(new URL('./src/utils', import.meta.url)),
        '@components': fileURLToPath(new URL('./src/components', import.meta.url)),
        '@config': fileURLToPath(new URL('./src/config', import.meta.url)),
        '@assets': fileURLToPath(new URL('./src/assets', import.meta.url)),
      },
    },
    define: {
      'process.env': process.env,
      __BUILD_TIME__: JSON.stringify(buildTime),
    },
    build: {
      chunkSizeWarningLimit: 1500,
      cssCodeSplit: true,
      rollupOptions: {
        output: {
          // manualChunks(id) {
          //   if (id.includes('node_modules')) {
          //     return '__vendor'
          //   }
          // },

          entryFileNames: 'js/[name].[hash].js',

          assetFileNames: '[ext]/[name].[hash].[ext]',

          chunkFileNames: () => `js/[name].[hash].js`,
        },
      },
    },

    server: {
      port: 8080,
      open: true,
      host: '0.0.0.0',
    },
  })
}
